package com.assets.Fragment;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.HandlerThread;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.assets.Check.newTanWanCheck.New_Check_choose;
import com.assets.Check.offlineCheck.OfflineCheckActivity;
import com.assets.Check.offlineCheck.OfflineCheckData;
import com.assets.MainActivity;
import com.assets.bean.InventoryDataBean;
import com.assets.newNHF.UhfApplication;
import com.assets.newNHF.util.LogUtils;
import com.assets.room.dao.CheckDao;
import com.assets.room.database.MyDataBase;
import com.assets.room.entity.Asset;
import com.assets.room.entity.Check;
import com.assets.room.entity.CheckData;
import com.assets.room.entity.Dept;
import com.assets.room.entity.Place;
import com.assets.room.entity.Receives;
import com.assets.room.entity.ReceivesDetail;
import com.assets.room.entity.ReceivesReapply;
import com.assets.room.entity.Type;
import com.assets.room.entity.User;
import com.assets.util.MyOkHttp;
import com.assets.util.Since_case;
import com.assets.util.TrustAllCerts;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.demo.WaveSwipeRefreshLayout;
import com.assets.Adapter.Check_adapter;
import com.assets.Check.Check_choose;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.bean.fragmentfor_bean;
import com.assets.menu.SlideSideMenuExampleActivity;
import com.google.gson.Gson;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/12/25.
 * 盘点
 */
public class Fragment4 extends Fragment {
    private static final String TAG = "jiangjianhua";
    private ImageView imageView, screen;
    private ListView listView;
    private SlideSideMenuExampleActivity mainActivity;
    private WaveSwipeRefreshLayout mWaveSwipeRefreshLayout;
    private String downloadDataUrl = "http://" + Url.IP + "/api/getAllAssetData";

    private String sendDataUrl = "http://" + Url.IP + "/api/sendAllAssetData";
    private String url = "http://" + Url.IP + "/api/checkQuery";
    private List<Map<String, Object>> list = new ArrayList<>();
    private List<Map<String, Object>> newList = new ArrayList<>();

    private List<Map<String, Object>> underway = new ArrayList<>();//待盘点
    private List<Map<String, Object>> Have_inventory = new ArrayList<>();//已盘点
    private List<Map<String, Object>> For_inventory = new ArrayList<>();//待盘点
    private HandlerThread handlerThread;

    private SlideSideMenuExampleActivity activity;
    private Handler handler;

    private MyDataBase db;
    private Button getAllTaskBtn;
    private ProgressBar downloadBar;
    private Dialog dialog;
    private Button butAllTaskBtn;
    private List<Type> typeList;
    private List<Place> placeList;
    private List<CheckData> checkDataList;
    private List<Check> checkList;
    private List<User> userList;
    private List<Dept> deptList;
    private List<Asset> assetList;
    private List<Receives> receivesList;
    private List<ReceivesDetail> receivesDetailList;
    private List<ReceivesReapply> receivesReapplyList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        activity = (SlideSideMenuExampleActivity) getActivity();
        View view = inflater.inflate(R.layout.fragment_second4, null);
        getAllTaskBtn = view.findViewById(R.id.btn_get_task);
        butAllTaskBtn = view.findViewById(R.id.btn_put_task);
        return view;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mainActivity = (SlideSideMenuExampleActivity) getActivity();
        init();
        setOnClickListener();
        listView = (ListView) getActivity().findViewById(R.id.checklist);
        handlerThread = new HandlerThread("word");
        handlerThread.start();
        handler = new Handler(handlerThread.getLooper());
//        handler.postDelayed(this::load, 200);
        listView.setOnItemClickListener((parent, view, i, id) -> {
            String checkId = (String) newList.get(i).get("odd");
            String checkStatus = (String) newList.get(i).get("checkStatus");
            String PlanRange = (String) newList.get(i).get("scope");
//            if (PlanRange.equals("闲置") || PlanRange.equals("存放地点")) {
//                Intent intent = new Intent(mainActivity, Check_choose.class);
//                intent.putExtra("checkId", checkId);
//                intent.putExtra("checkStatus", checkStatus);
//                intent.putExtra("isEdit", "0");
//                startActivity(intent);
//                LogUtils.d("闲置");
//                return;
//            }
//            LogUtils.d("checkId" + checkId + "checkStatus" + checkStatus);
//            if (checkStatus.equals("2")) {
//                Intent intent = new Intent(mainActivity, Check_choose.class);
//                intent.putExtra("checkId", checkId);
//                intent.putExtra("checkStatus", checkStatus);
//                startActivity(intent);
//                return;
//            }
//            //这里有bug   获取的checkDetailIds数据不对  获取checkDetailIds获取的盘点详情不对
//            if (checkStatus.equals("3")) {
//                String checkDetailIds = "[" + (String) list.get(i).get("checkDetailIds") + "]";
//                String deptId = (String) list.get(i).get("deptId");
//                LogUtils.d(MyOkHttp.getInstance().getGson().toJson(list.get(i)));
//                Intent intent = new Intent(mainActivity, Check.class);
//                intent.putExtra("id", checkId);//checkDetailIds
//                intent.putExtra("checkId", checkDetailIds);
//                intent.putExtra("deptId", deptId);
//                startActivity(intent);
//                return;
//            }
            Intent intent = new Intent(mainActivity, com.assets.Check.Check.class);
            intent.putExtra("id", newList.get(i).get("odd").toString());
//            intent.putExtra("checkStatus", checkStatus);
            intent.putExtra("createDate", newList.get(i).get("Date_created").toString());
            intent.putExtra("checkNum", newList.get(i).get("sum").toString());
            intent.putExtra("createUser", newList.get(i).get("creator") == null ? "" : newList.get(i).get("creator").toString());
            startActivity(intent);
        });
        listView.setOnItemLongClickListener((parent, view, position, id) -> {
            /*mainActivity.showTipDialog(aBoolean -> {
                if (aBoolean) {
                    String checkId = (String) list.get(position).get("odd");
                    checkDetailQuery(checkId);
                }
            }, "离线盘点");*/
            return true;
        });
    }

    private void setOnClickListener() {

        getAllTaskBtn.setOnClickListener(view -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            LayoutInflater inflater = LayoutInflater.from(activity);
            View v = inflater.inflate(R.layout.layout_offline, null);

            @SuppressLint({"MissingInflatedId", "LocalSuppress"})
            TextView title = v.findViewById(R.id.download_title);
            Button btnOk = v.findViewById(R.id.download_btn_ok);
            Button btnCancel = v.findViewById(R.id.download_btn_cancel);
            downloadBar = v.findViewById(R.id.download_pb);

            dialog = builder.create();
            dialog.show();
            dialog.getWindow().setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面

            btnOk.setOnClickListener(dialogBtnOk -> {


                //点击显示进度条
                downloadBar.setVisibility(View.VISIBLE);

                //改变文字状态
                title.setText("正在下载中...");

                //隐藏两个按钮
                btnOk.setVisibility(View.GONE);
                btnCancel.setVisibility(View.GONE);


                // TODO: 2023/11/22 下载数据
                downloadData(downloadDataUrl);


                //关闭对话框
//                    dialog.dismiss();


            });

            btnCancel.setOnClickListener(dialogBtnCancel -> {

                //关闭对话框
                dialog.dismiss();

            });
        });

        butAllTaskBtn.setOnClickListener(view -> {

            activity.showDialog("正在上传");
            Toast.makeText(mainActivity, "你好", Toast.LENGTH_SHORT).show();

            Map<String, String> map = new HashMap<>();
            List<CheckData> checkData = MyDataBase.init(activity).checkDataDao().getAssetCheckByFlag("1");
            String checkDataBean = MyOkHttp.getInstance().getGson().toJson(checkData);
            List<Check> checks = MyDataBase.init(activity).checkDao().getCheckById("1");
            String checkBean = MyOkHttp.getInstance().getGson().toJson(checks);

            Log.d("看看要上传的数据是什么", "checkData: " +
                    checkDataBean + "checks: " + checkBean);

            map.put("checkDataList", checkDataBean);
            map.put("checkList", checkBean);

            //上传数据
            MyOkHttp.getInstance().post(sendDataUrl, map, new MyOkHttp.requestMessage() {
                @Override
                public void requestFail() {

                }

                @Override
                public void requestComplete() {

                }

                @Override
                public void requestSuccess(Response response) throws IOException {
                    activity.canDialog();
                }
            });

            //删除数据
            MyDataBase.init(activity).assetDao().deleteAllData();
            MyDataBase.init(activity).userDao().deleteAllData();
            MyDataBase.init(activity).deptDao().deleteAllData();
            MyDataBase.init(activity).checkDao().deleteAllData();
            MyDataBase.init(activity).checkDataDao().deleteAllData();
            MyDataBase.init(activity).typeDao().deleteAllData();
            MyDataBase.init(activity).placeDao().deleteAllData();


        });


    }

    private void load() {
        new Thread() {
            @Override
            public void run() {
//                try {
                newList.clear();
                List<Check> allCheck = MyDataBase.init(activity).checkDao().getAllCheck();

                if (allCheck == null && allCheck.size() == 0) {

                    mainActivity.runOnUiThread(() -> {

                        mainActivity.showToast("暂无盘点任务");

                    });
//                    mWaveSwipeRefreshLayout.setRefreshing(false); 1
                    return;
                }
                Log.d(TAG, "run: " + allCheck.toString());
                for (int i = 0; i < allCheck.size(); i++) {

                    /**
                     "PlanRange":"\u673A\u6784",
                     "date":"2023-08-08 00:00:00",
                     "checkStatus":"1",/
                     "num":6,
                     "createdate":"2023-08-08 16:16:33",
                     "range":"\u5E02\u573A\u76D1\u7763\u7BA1\u7406\u5C40",
                     "createuser":"\u738B\u98DE",
                     "checkId":202308080017,
                     "status":"\u5DF2\u76D8\u70B9"
                     */


                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("odd", allCheck.get(i).getCheckId() + "");//盘点单号
                    map.put("creator", MyDataBase.init(activity).userDao().getNameByIds(allCheck.get(i).getCreateUser()) == null ? "找不到此人" : MyDataBase.init(activity).userDao().getNameByIds(allCheck.get(i).getCreateUser()));
                    map.put("Date_created", allCheck.get(i).getCreateDate().substring(0, 10));
//                    map.put("creator", beans[i].getCreateuser());
                    map.put("sum",  MyDataBase.init(activity).checkDataDao().getAllAssetCheckData(allCheck.get(i).getCheckId()).size() + "");
//                    if (TextUtils.isEmpty(beans[i].getDate())) {
//                        map.put("Inventory_date", beans[i].getDate());
//                    } else {
//                        map.put("Inventory_date", beans[i].getDate().substring(0, 10));
//                    }
//                    //  map.put("scope", beans[i].getPlanRange());
                    map.put("scope", MyDataBase.init(activity).placeDao().getNameById(MyDataBase.init(activity).checkDataDao().getAssetCheckData(allCheck.get(i).getCheckId()).getPlace()));
//                    if (!TextUtils.isEmpty(beans[i].getRange())) {
//                        if (beans[i].getCheckStatus().equals("3")) {
//                            map.put("scope", beans[i].getRange());
//                        }
//                    }
//                    if (!TextUtils.isEmpty(beans[i].getCheckDetailIds())) {
//                        map.put("checkDetailIds", beans[i].getCheckDetailIds());
//                    }
//                    if (!TextUtils.isEmpty(beans[i].getDeptId())) {
//                        map.put("deptId", beans[i].getDeptId());
//                    }
                    map.put("state", allCheck.get(i).getStatus());
//                    map.put("checkStatus", beans[i].getCheckStatus());
                    //LogUtils.d(beans[i].getPlanRange());
                    //map.put("PlanRange",beans[i].getPlanRange());
                    newList.add(map);



                    activity.runOnUiThread(() -> {
                        Check_adapter re_ad = new Check_adapter(activity, newList);
                        listView.setAdapter(re_ad);
                        mWaveSwipeRefreshLayout.setRefreshing(false);
                    });


                }
//                    RequestBody requestBody = new FormBody.Builder()
//                            .add("userId", Since_case.getInstance().getUserId())
//                            .build();
//                    OkHttpClient client = new OkHttpClient
//                            .Builder()
//                            .hostnameVerifier(new AllowAllHostnameVerifier())
//                            .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
//                            .connectTimeout(10, TimeUnit.SECONDS)//连接超时
//                            .readTimeout(500, TimeUnit.SECONDS)
//                            .build();
//                    Request request = new Request.Builder()
//                            .url(url)
//                            .post(requestBody)
//                            .build();
//                    Response response = client.newCall(request).execute();
//                    String responseData = response.body().string();
//                    Log.d("responseData==", "responseData=" + responseData);
//                    LogUtils.d(responseData);
//                    showResponse(responseData);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
            }
        }.start();
    }

    private void showResponse(final String responseData) {
        //1是子公司的，2是事业部，3是使用部门
        list.clear();//停止加载动画
        if (responseData.equals("[]")) {
            mainActivity.showToast("无盘点单");
            mainActivity.runOnUiThread(() -> {
                mWaveSwipeRefreshLayout.setRefreshing(false);
            });
            return;
        }
        Gson gson = new Gson();
        fragmentfor_bean[] beans = gson.fromJson(responseData, fragmentfor_bean[].class);
        for (int i = beans.length - 1; i >= 0; i--) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("odd", beans[i].getCheckId());
            map.put("Date_created", beans[i].getCreatedate().substring(0, 10));
            map.put("creator", beans[i].getCreateuser());
            map.put("sum", beans[i].getNum());
            if (TextUtils.isEmpty(beans[i].getDate())) {
                map.put("Inventory_date", beans[i].getDate());
            } else {
                map.put("Inventory_date", beans[i].getDate().substring(0, 10));
            }
            //  map.put("scope", beans[i].getPlanRange());
            map.put("scope", beans[i].getRange());
            if (!TextUtils.isEmpty(beans[i].getRange())) {
                if (beans[i].getCheckStatus().equals("3")) {
                    map.put("scope", beans[i].getRange());
                }
            }
            if (!TextUtils.isEmpty(beans[i].getCheckDetailIds())) {
                map.put("checkDetailIds", beans[i].getCheckDetailIds());
            }
            if (!TextUtils.isEmpty(beans[i].getDeptId())) {
                map.put("deptId", beans[i].getDeptId());
            }
            map.put("state", beans[i].getStatus());
            map.put("checkStatus", beans[i].getCheckStatus());
            //LogUtils.d(beans[i].getPlanRange());
            //map.put("PlanRange",beans[i].getPlanRange());
            list.add(map);
        }
        Check_adapter re_ad = new Check_adapter(mainActivity, list);
        mainActivity.runOnUiThread(() -> {
            listView.setAdapter(re_ad);
            mWaveSwipeRefreshLayout.setRefreshing(false);
        });
    }

    private void init() {
        screen = (ImageView) mainActivity.findViewById(R.id.screen);
        TextView title = mainActivity.findViewById(R.id.title_text);
        title.setText("盘点");

        screen.setOnClickListener(v -> new AlertView("筛选", null, "取消", new String[]{"全部"}, new String[]{"已盘点", "待盘点", "进行中"}, mainActivity, AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    //适配器，刚刚重写的！
                    Check_adapter re_ad = new Check_adapter(mainActivity, newList);
                    listView.setAdapter(re_ad);
                }
                if (position == 1) {
                    Have_inventory.clear();
                    for (int i = 0; i < newList.size(); i++) {
                        if (newList.get(i).get("state").equals("已盘点")) {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("odd", newList.get(i).get("odd"));
                            map.put("Date_created", newList.get(i).get("Date_created"));
                            map.put("creator", newList.get(i).get("creator"));
                            map.put("sum", newList.get(i).get("sum"));
                            map.put("Inventory_date", newList.get(i).get("Inventory_date"));
                            map.put("scope", newList.get(i).get("scope"));
                            map.put("state", newList.get(i).get("state"));
                            Have_inventory.add(map);
                        }
                    }
                    Check_adapter re_ad = new Check_adapter(mainActivity, Have_inventory);
                    listView.setAdapter(re_ad);
                }
                if (position == 2) {
                    For_inventory.clear();
                    for (int i = 0; i < list.size(); i++) {
                        if (newList.get(i).get("state").equals("待盘点")) {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("odd", newList.get(i).get("odd"));
                            map.put("Date_created", newList.get(i).get("Date_created"));
                            map.put("creator", newList.get(i).get("creator"));
                            map.put("sum", newList.get(i).get("sum"));
                            map.put("Inventory_date", newList.get(i).get("Inventory_date"));
                            map.put("scope", newList.get(i).get("scope"));
                            map.put("state", newList.get(i).get("state"));
                            For_inventory.add(map);
                        }
                    }
                    Check_adapter re_ad = new Check_adapter(mainActivity, For_inventory);
                    listView.setAdapter(re_ad);
                }
                if (position == 3) {
                    underway.clear();
                    for (int i = 0; i < newList.size(); i++) {
                        if (newList.get(i).get("state").equals("进行中")) {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("odd", newList.get(i).get("odd"));
                            map.put("Date_created", newList.get(i).get("Date_created"));
                            map.put("creator", newList.get(i).get("creator"));
                            map.put("sum", newList.get(i).get("sum"));
                            map.put("Inventory_date", newList.get(i).get("Inventory_date"));
                            map.put("scope", newList.get(i).get("scope"));
                            map.put("state", newList.get(i).get("state"));
                            underway.add(map);
                        }
                    }
                    underway.toString();
                    Check_adapter re_ad = new Check_adapter(mainActivity, underway);
                    listView.setAdapter(re_ad);
                }
            }
        }).show());
        imageView = (ImageView) getActivity().findViewById(R.id.opmenu);
        imageView.setOnClickListener((View.OnClickListener) v -> {
            SlideSideMenuTransitionLayout mSlideSideMenu = (SlideSideMenuTransitionLayout) getActivity().findViewById(R.id.slide_side_menu);
            mSlideSideMenu.toggle();
        });

        mWaveSwipeRefreshLayout = (WaveSwipeRefreshLayout) getActivity().findViewById(R.id.main_swipe);
        mWaveSwipeRefreshLayout.setColorSchemeColors(Color.WHITE, Color.WHITE);//设置水滴中旋转动画的颜色，参数1:水滴落下过程中的颜色，参数2:水滴已经落下后的颜色
        mWaveSwipeRefreshLayout.setWaveColor(0xFF3794fc);//设置水滴样色
        mWaveSwipeRefreshLayout.setMaxDropHeight(1500);//设置最大下拉高度
        mWaveSwipeRefreshLayout.setOnRefreshListener(() -> {
            //模拟3秒的加载过程
            //接下来可以刷新ListView
            new Handler().postDelayed(this::load, 1200);
        });

    }

    private void checkDetailQuery(String checkId) {
        Map<String, String> map = new HashMap<>();
        map.put("checkId", checkId);

    }

    @Override
    public void onStart() {
        if (handler != null) {
            handler.postDelayed(this::load, 300);
        }
        LogUtils.d("onStart");
        super.onStart();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        handlerThread.quit();
        LogUtils.d("onDestroy");
    }


    private void downloadData(String url) {

        MyOkHttp.getInstance().get(url, new MyOkHttp.requestMessage() {
            private InventoryDataBean inventoryDataBean;


            @Override
            public void requestFail() {

            }

            @Override
            public void requestComplete() {

            }

            @Override
            public void requestSuccess(Response response) throws IOException {

                response.header("Content-Type");
//                 String responseData = response.body().string();
                // 使用指定的字符编码解码数据
                String result = response.body().string();

//                long length = response.body().contentLength();
                if (!response.isSuccessful()) {
//                    showToast("连接服务器失败!");
                } else {

                    Log.d(TAG, "result: " + result);

                    inventoryDataBean = MyOkHttp.getInstance().getGson().fromJson(result, InventoryDataBean.class);

//                    Log.d(TAG, "inventoryDataBean: " + inventoryDataBean.toString());

                    if (inventoryDataBean.getStatus() == 0) {
                        mainActivity.showToast("暂无盘点任务");
                        dialog.dismiss();
                        return;
                    }
                    insertData(inventoryDataBean);

                }

            }
        });

    }

    private void insertData(InventoryDataBean bean) {


        Log.d(TAG, "getReceivesList: " + bean.getReceivesList().toString() +
                ",getReceivesDetailList: " + bean.getReceivesDetailList().toString() +
                ",getReceivesReapplyList: " + bean.getReceivesReapplyList().toString());
        bean.getReceivesList().toString();
        bean.getReceivesDetailList().toString();
        bean.getReceivesReapplyList().toString();


        if (bean.getReceivesReapplyList() == null) {
            MyDataBase.init(activity).receivesReapplyDao().insertReceivesReapply(new ReceivesReapply());
        }else {
            List<InventoryDataBean.ReceivesReapplyDTO> receivesReapplyDTO = bean.getReceivesReapplyList();
            receivesReapplyList = receivesReapplyDTO.stream().map(bean3 -> {
                ReceivesReapply receivesReapply = new ReceivesReapply();
                receivesReapply.setId(bean3.getId());
                receivesReapply.setReceivesId(Long.valueOf(bean3.getReceivesId()));
                receivesReapply.setName(bean3.getName());
                receivesReapply.setNum(bean3.getNum());
                receivesReapply.setIsaudit(bean3.getIsaudit());
                receivesReapply.setUnaudit(bean3.getUnaudit());
                receivesReapply.setUser(bean3.getUser());
                receivesReapply.setPlace(bean3.getPlace());
                receivesReapply.setSum(bean3.getSum());
                receivesReapply.setIsput(bean3.getIsput());
                receivesReapply.setIsFlag("0");
                return receivesReapply;
            }).collect(Collectors.toList());
            MyDataBase.init(activity).receivesReapplyDao().insertReceivesReapply(receivesReapplyList);
        }

        if (bean.getReceivesDetailList() == null) {
            MyDataBase.init(activity).receivesDetailDao().insertReceivesDetail(new ReceivesDetail());
        }else {
            List<InventoryDataBean.ReceivesDetailDTO> receivesDetailDTO = bean.getReceivesDetailList();
            receivesDetailList = receivesDetailDTO.stream().map(bean2 -> {
//                Long receivesDetailId, String receivesId, String assetId, String isreturn, String isFlag
                ReceivesDetail receivesDetail = new ReceivesDetail();

                receivesDetail.setReceivesDetailId(Long.valueOf(bean2.getReceivesDetailId()));
                receivesDetail.setReceivesId(bean2.getReceivesId());
                receivesDetail.setAssetId(bean2.getAssetId());
                receivesDetail.setIsreturn(bean2.getIsreturn());
                receivesDetail.setIsFlag("0");

                return receivesDetail;
            }).collect(Collectors.toList());
            MyDataBase.init(activity).receivesDetailDao().insertReceivesDetail(receivesDetailList);
        }


        if (bean.getReceivesList() == null) {
            MyDataBase.init(activity).receivesDao().insertReceive(new Receives());
        }else {
            List<InventoryDataBean.ReceivesListDTO> receivesDTO = bean.getReceivesList();
            receivesList = receivesDTO.stream().map(receivesBean -> {
                Receives receives = new Receives();
                receives.setReceivesId(Long.valueOf(receivesBean.getReceivesId()));
                receives.setReceivesDept(receivesBean.getReceivesDept());
                receives.setReapplyDate(receivesBean.getReapplyDate());
                receives.setReceivesRemark(receivesBean.getReceivesRemark());
                receives.setStatus(receivesBean.getStatus());
                receives.setReceivesDate(receivesBean.getReceivesDate());
                receives.setIsreturn(receivesBean.getIsreturn());
                receives.setText(receivesBean.getText());
                receives.setPlace(receivesBean.getPlace());
                receives.setCompany(receivesBean.getCompany());
                receives.setDivision(receivesBean.getDivision());
                receives.setCreateuser(receivesBean.getCreateuser());
                receives.setIsFlag("0");

                return receives;
            }).collect(Collectors.toList());
            MyDataBase.init(activity).receivesDao().insertReceive(receivesList);
        }


        List<InventoryDataBean.AssetListDTO> assetDTO = bean.getAssetList();
        if (assetDTO.size() == 0) {

        }else {
            assetList = assetDTO.stream().map(assetListDTO -> {
                Asset asset = new Asset();
                asset.setAssetId(assetListDTO.getAssetId().equals("") ? 0 : Long.valueOf(assetListDTO.getAssetId()));
                asset.setAssetNumber(assetListDTO.getAssetNumber());
                asset.setUserId(assetListDTO.getUserId());
                asset.setDeptId(assetListDTO.getDeptId());
                asset.setAssetName(assetListDTO.getAssetName());
                asset.setModel(assetListDTO.getModel());
                asset.setType(assetListDTO.getType());
                asset.setStatus(assetListDTO.getStatus());
                asset.setGrundlagen(assetListDTO.getGrundlagen());
                asset.setUnit(assetListDTO.getUnit());
                asset.setAmount("".equals(assetListDTO.getAmount()) ? 0L : Double.valueOf(assetListDTO.getAmount()));
                asset.setCreatedate(assetListDTO.getCreatedate());
                asset.setRemark(assetListDTO.getRemark());
                asset.setPlace(assetListDTO.getPlace());
                asset.setImage(assetListDTO.getImage());
                asset.setYear("".equals(assetListDTO.getYear()) ? 0L : Double.valueOf(assetListDTO.getYear()));
                asset.setSalvage("".equals(assetListDTO.getSalvage()) ? 0L : Double.valueOf(assetListDTO.getSalvage()));
                asset.setRfid(assetListDTO.getRfid());
                asset.setReceivesdate(assetListDTO.getReceivesdate());
                asset.setReceiver(assetListDTO.getReceiver());
                asset.setTeam(assetListDTO.getTeam());
                asset.setCompany(assetListDTO.getCompany());
                asset.setUserDept(assetListDTO.getUserDept());
                asset.setDivision(assetListDTO.getDivision());
                asset.setArea(assetListDTO.getArea());
                asset.setAdmin(assetListDTO.getAdmin());
                asset.setSource(assetListDTO.getSource());
                asset.setSupplier(assetListDTO.getSupplier());
                asset.setUsedate(assetListDTO.getUsedate());
                asset.setFinancialCode(assetListDTO.getFinancialCode());
                asset.setCreateUser(assetListDTO.getCreateUser());
                asset.setBrand(assetListDTO.getBrand());
                asset.setAduit(assetListDTO.getAduit());
                asset.setIsPrint(assetListDTO.getIsPrint());
                asset.setAreavalue("".equals(assetListDTO.getAreavalue()) ? 0L : Double.valueOf(assetListDTO.getAreavalue()));
                asset.setAccountant(assetListDTO.getAccountant());
                asset.setTypex(assetListDTO.getTypex());
                asset.setIsFlag(assetListDTO.getIsPrint());
                return asset;
            }).collect(Collectors.toList());
        }



        List<InventoryDataBean.DeptListDTO> deptDTO = bean.getDeptList();
        if (deptDTO.size() == 0){

        }else {
            deptList = deptDTO.stream().map(data -> {

                Dept dept = new Dept();
                dept.setDeptId("".equals(data.getDeptId()) ? 0L : Long.valueOf(data.getDeptId()));
                dept.setPid("".equals(data.getPid()) ? 0L : Long.valueOf(data.getPid()));
                dept.setPids(data.getPids());
                dept.setSimpleName(data.getSimpleName());
                dept.setFullName(data.getFullName());
                dept.setDescription(data.getDescription());
                dept.setVersion(0);
                dept.setSort("".equals(data.getSort()) ? 0 : Integer.parseInt(data.getSort()));
                dept.setCreateTime(data.getCreateTime());
                dept.setUpdateTime(data.getUpdateTime());
                dept.setCreateUser("".equals(data.getCreateUser()) ? 0L : Long.valueOf(data.getCreateUser()));
                dept.setUpdateUser("".equals(data.getUpdateUser()) ? 0L : Long.valueOf(data.getUpdateUser()));
                dept.setIsFlag("0");
                return dept;
            }).collect(Collectors.toList());
        }


        List<InventoryDataBean.UserListDTO> userDTO = bean.getUserList();
        if (userDTO.size() == 0) {

        }else {
            userList = userDTO.stream().map(bean2 -> {
                User user = new User();
                user.setUserId("".equals(bean2.getUserId()) ? 0L : Long.valueOf(bean2.getUserId()));
                user.setAvatar(bean2.getAvatar());
                user.setAccount(bean2.getAccount());
                user.setPassword(bean2.getPassword());
                user.setSalt(bean2.getSalt());
                user.setName(bean2.getName());
                user.setBirthday(bean2.getBirthday());
                user.setSex(bean2.getSex());
                user.setEmail(bean2.getEmail());
                user.setPhone(bean2.getPhone());
                user.setRoleId(bean2.getRoleId());
                user.setCreateTime(bean2.getCreateTime());
                user.setCreateUser("".equals(bean2.getCreateUser()) ? 0L : Long.valueOf(bean2.getCreateUser()));
                user.setUpdateTime(bean2.getUpdateTime());
                user.setUpdateUser("".equals(bean2.getUpdateUser()) ? 0L : Long.valueOf(bean2.getUpdateUser()));
                user.setVersion(0);
                user.setData(bean2.getData());
                user.setIsFlag("0");


                return user;
            }).collect(Collectors.toList());

        }


        if (bean.getCheckList() == null) {
            MyDataBase.init(activity).checkDao().insertCheck(new Check());
        }else {
            List<InventoryDataBean.CheckListDTO> checkDTO = bean.getCheckList();
            checkList = checkDTO.stream().map(bean3 -> {
                Check check = new Check();


                check.setCheckId(bean3.getCheckId());
                check.setCheckFlag(Long.valueOf(bean3.getCheckFlag()));
                check.setPlanRange(bean3.getPlanRange());
                check.setConcreteRange(bean3.getConcreteRange());
                check.setCheckDate(bean3.getCheckDate());
                check.setStatus(bean3.getStatus());
                check.setCreateUser(bean3.getCreateUser());
                check.setCreateDate(bean3.getCreateDate());
                check.setRemark(bean3.getRemark());
                check.setFlag("0");

                return check;
            }).collect(Collectors.toList());
            MyDataBase.init(activity).checkDao().insertCheck(checkList);
        }



        if (bean.getCheckDataList() == null) {
            MyDataBase.init(activity).checkDataDao().insertCheckData(new CheckData());
        }else {
            List<InventoryDataBean.CheckDataListDTO> checkDataDTO = bean.getCheckDataList();
            checkDataList = checkDataDTO.stream().map(bean4 -> {
                CheckData checkData = new CheckData();
                checkData.setCheckDataId(bean4.getCheckDataId());
                checkData.setCheckId("".equals(bean4.getCheckId()) ? 0L : Long.valueOf(bean4.getCheckId()));
                checkData.setCheckFlag("".equals(bean4.getCheckFlag()) ? 0L : Long.valueOf(bean4.getCheckFlag()));
                checkData.setAssetNumber(bean4.getAssetNumber());
                checkData.setAssetName(bean4.getAssetName());
                checkData.setModel(bean4.getModel());
                checkData.setType(bean4.getType());
                checkData.setCheckResult(bean4.getCheckResult());
                checkData.setPlace(bean4.getPlace());
                checkData.setFlag("0");
                return checkData;
            }).collect(Collectors.toList());
            MyDataBase.init(activity).checkDataDao().insertCheckData(checkDataList);
        }


        List<InventoryDataBean.PlaceListDTO> placeDTO = bean.getPlaceList();
        if (placeDTO.size() == 0) {

        }else {
            placeList = placeDTO.stream().map(bean4 -> {
                Place place = new Place();
                place.setId(bean4.getId());
                place.setName(bean4.getName());
                place.setBig(bean4.getBig());
                place.setRemark(bean4.getRemark());
                place.setPid(bean4.getPid());
                place.setFlag("0");
                return place;
            }).collect(Collectors.toList());
        }


        List<InventoryDataBean.TypeListDTO> typeDTO = bean.getTypeList();
        if (typeDTO.size() == 0) {

        }else {
            typeList = typeDTO.stream().map(bean5 -> {
                Type type = new Type();
                type.setId(Long.valueOf(bean5.getId()));
                type.setTypenum(bean5.getTypenum());
                type.setName(bean5.getName());
                type.setRemark(bean5.getRemark());
                type.setPid(bean5.getPid());
                type.setFlag("0");

                return type;
            }).collect(Collectors.toList());
        }



        MyDataBase.init(activity).assetDao().insertAsset(assetList);
        MyDataBase.init(activity).deptDao().insertDept(deptList);
        MyDataBase.init(activity).userDao().insertUser(userList);
        MyDataBase.init(activity).placeDao().insertPlace(placeList);
        MyDataBase.init(activity).typeDao().insertType(typeList);

        dialog.dismiss();

//        Intent intent = new Intent(mainActivity, Check_choose.class);
//        intent.putExtra("checkId", checkId);
//        intent.putExtra("checkStatus", checkStatus);
//        startActivity(intent);



    }





}
